package com.tj.jinzao.base;

import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.util.ArrayMap;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;

import com.tj.jinzao.common.Constant;
import com.tj.jinzao.utils.Utils;
import com.tj.jinzao.widgets.EmptyView;

import java.util.Map;

/**
 * 所有绑定Cursor的带刷新的listView的fragment基类
 * Created by wjy on 2016/3/25.
 */
public abstract class BaseCursorListFragment<T,V extends BasePresenter> extends BaseListFragment<T,V> implements LoaderManager.LoaderCallbacks<Cursor> {

    protected final static String ARG_TAG_ID = "tagId";
    protected String mTag;//参数

    protected int mLoadType;//数据库loader参数

    protected Cursor mCursor;

    protected RecyclerViewCursorAdapter mCursorAdapter;

    //支持同时多个查询loaderId
    protected Map<Integer, Cursor> mCursorMap;

    protected Map<Integer, RecyclerViewCursorAdapter> mCursorAdapterMap;

    /**
     * @param loadId   数据库loader
     * @param tagId    自定义参数 比如articleId
     * @param layoutId 布局文件
     * @param fragment 类对象
     * @return
     */
    public static BaseCursorListFragment newInstance(int loadId, String tagId, int layoutId, BaseCursorListFragment fragment) {
        if (fragment != null) {
            Bundle args = new Bundle(3);
            args.putString(ARG_TAG_ID, tagId);
            args.putInt(ARG_LOAD_ID, loadId);
            args.putInt(ARG_LAYOUT_RES_ID, layoutId);
            fragment.setArguments(args);
        }
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mLoadType = getArguments().getInt(ARG_LOAD_ID);
        mLayoutResId = getArguments().getInt(ARG_LAYOUT_RES_ID);
        mTag = getArguments().getString(ARG_TAG_ID);
        mLoaderId = mLoadType + Utils.parseInt(mTag);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        createActivity();
    }

    @Override
    protected void createActivity() {
        super.createActivity();
        if (needQueryMoreCursor()) {
            mCursorMap = new ArrayMap();
            mCursorAdapterMap = new ArrayMap();
        }
        mCursorAdapter.setRecyclerView(mListView);
        initLoader();
    }

    @Override
    protected RecyclerView.Adapter createAdapter() {
        mCursorAdapter = createCursorAdapter();
        return mCursorAdapter;
    }

    protected boolean needQueryMoreCursor() {
        return false;
    }

    @Override
    public void onItemClick(View view, int position) {
        if (moveCursorIndex(mCursor, position, mListView.getHeaderSize())) {
            itemClicked(mCursor);
        }
    }

    @Override
    public void onItemLongClick(View view, int position) {
        if (moveCursorIndex(mCursor, position, mListView.getHeaderSize())) {
            itemLongClicked(mCursor);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != mCursorAdapter) {
            mCursorAdapter.swapCursor(null);
        }
    }

    abstract protected RecyclerViewCursorAdapter createCursorAdapter();

    abstract protected Loader<Cursor> createLoader(int id, Bundle bundle);

    abstract protected void itemClicked(Cursor cursor);

    protected void itemLongClicked(Cursor cursor) {

    }

    @Override
    protected boolean hasData() {
        return mCursor != null && mCursor.getCount() > 0;
    }

    /**
     * 加载数据库完成
     *
     * @param cursor
     */
    protected void loadFinish(Cursor cursor) {
        if (null != cursor) {
            mCursorAdapter.swapCursor(cursor);
            int count = cursor.getCount();
            if (0 == count) {
                if (Constant.TRACE) Log.d(TAG, "loadFinish count is 0, mLoading:"
                        + mLoading + ",mInitialize:" + mInitialize);
                if (mLoading || !mInitialize) {
                    setEmptyView(EmptyView.State.LOADING, false);
                } else {
                    mEmptyView.setVisibility(View.VISIBLE);
                    mListView.setVisibility(View.INVISIBLE);
                    setEmptyDataView();
                }
            } else {
                mListView.setVisibility(View.VISIBLE);
                mEmptyView.setVisibility(View.INVISIBLE);
                setFooterVisibility();
            }
            try {
                mListView.getAdapter().notifyDataSetChanged();
            } catch (Exception e) {
                e.printStackTrace();
            }
            //关闭加载
            closeRefresh();
        }
    }

    /**
     * 点击item时，index需要减去headView
     *
     * @param position
     * @param headViewSize
     * @return
     */
    protected boolean moveCursorIndex(Cursor cursor, int position, int headViewSize) {
        position = Math.max(0, position - headViewSize);
        if (!(cursor != null && cursor.moveToPosition(position))) {
            return false;
        } else {
            return true;
        }
    }

    protected void initLoader() {
        getLoaderManager().initLoader(mLoaderId, null, this);
    }

    public void restartLoader(int loaderId) {
        try {
            getLoaderManager().restartLoader(loaderId, null, this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle bundle) {
        CursorLoader loader = (CursorLoader) createLoader(id, bundle);
        // Update at most every 300.
        if (loader != null) loader.setUpdateThrottle(300);
        return loader;
    }

    public void addOtherLoader(int otherId, RecyclerViewCursorAdapter adapter) {
        getLoaderManager().initLoader(otherId, null, this);
        mCursorAdapterMap.put(otherId, adapter);
    }

    @Override
    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
        if (cursorLoader.getId() != mLoaderId) {
            mCursorMap.put(cursorLoader.getId(), cursor);
            loadOtherFinish(cursorLoader.getId(), cursor);
        } else if (null != cursor) {
            mCursor = cursor;
            loadFinish(cursor);
        }
    }

    protected void loadOtherFinish(int loadId, Cursor cursor) {
    }

    @Override
    public void onLoaderReset(Loader<Cursor> cursorLoader) {
        if (cursorLoader.getId() != mLoaderId) {
            RecyclerViewCursorAdapter cursorAdapter = mCursorAdapterMap.get(cursorLoader.getId());
            if (null != cursorAdapter) {
                cursorAdapter.swapCursor(null);
                return;
            }
        }
        if (null != mCursorAdapter) mCursorAdapter.swapCursor(null);
    }
}
